package com.lambkit.core;

import cn.hutool.core.collection.CollUtil;
import com.lambkit.core.pipeline.PipeLineContext;
import com.lambkit.core.pipeline.Valve;
import com.lambkit.util.Printer;

import java.util.List;

/**
 * @author yangyong(孤竹行)
 */
public class AppCreateValve extends Valve {
    @Override
    public void invoke(PipeLineContext context, boolean isHandled) {
        List<Class<? extends LambkitApp>> lambkitAppClassList = context.getAttr("lambkitAppClassList");
        if(lambkitAppClassList == null || lambkitAppClassList.size()==0) {
            Printer.print(this, "starter", "None App was find, Then starting default lambkit app {}.", DefaultLambkitApp.class.getName());
            lambkitAppClassList = CollUtil.newArrayList();
            lambkitAppClassList.add(DefaultLambkitApp.class);
        }
        for (Class<? extends LambkitApp> lambkitAppClass : lambkitAppClassList) {
            String name = appName(lambkitAppClass);
            createApp(name, lambkitAppClass);
        }
        next(context, isHandled);
    }

    public String appName(Class<? extends LambkitApp> appClass) {
        String name = LambkitContext.MAIN_APP;
        if(Lambkit.app() != null) {
            name = "app" + Lambkit.context().appSize() + "_" + appClass.getSimpleName();
        }
        return name;
    }

    public LambkitApp createApp(String name, Class<? extends LambkitApp> appClass)  {
        return Lambkit.context().createApp(name, appClass);
    }
}
